<?php

class multitender_action_load_seo_keys extends multitender_action {

    private $form = "<form action='' method='post' enctype='multipart/form-data'>
                        Выберите фаил (UTF-8), фильтр по словам (госзакуп|госзаказ|тендер):<br>

                        <input type='file' name='filename'>

                        <br />
                        <label>Загрузка ключей для проекта</label>
                        <select name='type'>
                            <option value='1'>ДЛЯ MULTITENDER.RU</option>
                            <option value='2'>ВНЕШНИЕ ССЛЫКИ</option>
                        </select>

                        <br />
                        <input type='checkbox' name='old_clear' id='old_clear' /><label for='old_clear'>Очистить старые</label>

                        <br />
                        <input type='submit' name='load' value='загрузить' />
                    </form>";

    private $tbl_seo_text = "seo_text";

    function __construct() {
        parent::__construct();
        $rights = $this->conf['user']['right'];
        if ($rights<=50) {
            echo("ДОСТУП ЗАКРЫТ");
            exit;
        }
        $this->db = ADONewConnection($this->conf['db_conf']['joomla']['dsn']);
        $this->db->Execute('set names utf8');
    }

    private function clear_line($text) {
        $s_n_r = array(
                "#\h+#u"   => " ",
                "#^\s+#mu" => "",
                "#\s+$#mu" => "",
        );

        $text = preg_replace(array_keys($s_n_r), array_values($s_n_r), $text);
        return $text;
    }

    function run() {
        echo("<h1>Загрузка SEO ключей</h1>");
        if (!empty($_POST['load']) && !empty($_FILES["filename"]) && ($_FILES["filename"]["size"] > 0)) {
            $filename = $_FILES["filename"]["name"];

            $lines = file($_FILES["filename"]["tmp_name"]);
            shuffle($lines);
            $hrefs = array();
            foreach ($lines as $line) {               
                if (!preg_match("#(http://.+?):(.+)#i", $line, $p)) { continue; }
                $words = trim($p[2]);
                foreach (explode("|", $words) as $word)  { $hrefs[] = "<a href=\"{$p[1]}\">$word</a>"; }
            }
            
            $type = (int) isset($_POST['type']) ? $_POST['type'] : 1;
            if (isset($_POST['old_clear'])) {
                $this->db->Execute("DELETE FROM seo_text WHERE type=?", array($type));
            }

            foreach ($hrefs as $line) {                
                $line = $this->clear_line($line);
                $crc = crc_p(mb_strtolower($line, 'UTF-8'));
                if (!$this->db->GetOne("SELECT crc FROM $this->tbl_seo_text WHERE crc=$crc")) {
                    $this->db->Execute("INSERT INTO $this->tbl_seo_text(crc, text, type) VALUES(?,?,?)", array($crc, $line, $type));
                }
            }
            echo("<h1 style='color: green'>Файл успешно загружен</h1>");
            echo("<hr />");
        }

        echo $this->form;
    }
}
